package de.unibi.mmi.homeauto.team1.drafts;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import de.unibi.mmi.homeauto.team1.R;
import de.unibi.mmi.homeauto.team1.mainview.MainViewActivity;

public abstract class ImageFragment extends DraftFragment {

	ImageFragment bla = this;

	protected Symbol[] symbols;
	protected int numColumns = 3;

	protected double widthFrac = numColumns + 0.5d;

	private GridView gridView;

	private ImageAdapter adapter;

	public class Symbol {

		private int imageID;
		private int screen;
		private int item;

		public Symbol(final int texture, final int whichScreen,
				final int itemOnScreen) {
			this.imageID = texture;
			this.screen = whichScreen;
			this.item = itemOnScreen;
		}
	}

	@Override
	protected final int getLayoutID() {
		return R.layout.image;
	}

	protected void updateView() {
		adapter.notifyDataSetChanged();
		gridView.setAdapter(adapter);
	}

	@Override
	protected final void loadComponents(View view) {
		adapter = new ImageAdapter(this.getActivity());
		gridView = (GridView) view.findViewById(R.id.gridview);
		gridView.setNumColumns(numColumns);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				((MainViewActivity) getActivity()).changeScreen(
						symbols[position].screen, symbols[position].item);
			}
		});

	}

	public class ImageAdapter extends BaseAdapter {
		private Context context;

		public ImageAdapter(Context c) {
			context = c;
		}

		public int getCount() {
			return symbols.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(context);
				int imageWidth = (int) (((double) ((MainViewActivity) getActivity())
						.getMainWidth()) / (widthFrac));
				imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
						imageWidth));
				imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				imageView.setPadding(10, 10, 10, 10);
			} else {
				imageView = (ImageView) convertView;
			}
			imageView.setImageResource(symbols[position].imageID);
			return imageView;
		}
	}

}